#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QSqlDatabase db = QSqlDatabase::addDatabase("QODBC");
    db.setHostName("47.107.92.191");
    db.setPort(1314);
    db.setDatabaseName("winzhiang");
    db.setUserName("winzhiang");
    db.setPassword("Aa12345678.");
    bool ok = db.open();
    if (ok){
        QMessageBox::information(this, "infor", "success");
    }
    else {
        QMessageBox::information(this, "infor", "open failed");
        qDebug()<<"error open database because"<< db.lastError().text();
    }
    //查询数据库中所有表的名称
    QStringList tables = db.tables();
    foreach(QString table, tables)
        qDebug()<<table;

    //ODBC查询数据
    QSqlQuery result = db.exec(" select * from users");
    while(result.next()){
        qDebug()<<"id:"<<result.value("id").toInt();
        qDebug()<<"name:"<<result.value("name").toString();
        qDebug()<<"age:"<<result.value("age").toString();
        qDebug()<<"phone:"<<result.value("phone").toInt();
    }

}

Widget::~Widget()
{
    delete ui;
}
